import 'package:get/get.dart';
import 'package:flutter/material.dart';

import '../../models/virtual_file_node.dart';
import '../../models/file_metadata.dart';
import '../../services/database_service.dart';
import '../../services/tianyi_cloud_service.dart';
import '../../services/file_manager_service.dart';
import '../../services/preferences_service.dart';

enum SearchScope {
  local,
  cloud,
  all,
}

enum SearchType {
  all,
  folder,
  image,
  video,
  audio,
  document,
  archive,
  other,
}

class SearchFilter {
  final SearchScope scope;
  final SearchType type;
  final DateTime? startDate;
  final DateTime? endDate;
  final int? minSize;
  final int? maxSize;
  final String? path;
  
  SearchFilter({
    this.scope = SearchScope.all,
    this.type = SearchType.all,
    this.startDate,
    this.endDate,
    this.minSize,
    this.maxSize,
    this.path,
  });
  
  SearchFilter copyWith({
    SearchScope? scope,
    SearchType? type,
    DateTime? startDate,
    DateTime? endDate,
    int? minSize,
    int? maxSize,
    String? path,
  }) {
    return SearchFilter(
      scope: scope ?? this.scope,
      type: type ?? this.type,
      startDate: startDate ?? this.startDate,
      endDate: endDate ?? this.endDate,
      minSize: minSize ?? this.minSize,
      maxSize: maxSize ?? this.maxSize,
      path: path ?? this.path,
    );
  }
}

class SearchController extends GetxController {
  final DatabaseService _databaseService = Get.find<DatabaseService>();
  final TianyiCloudService _cloudService = Get.find<TianyiCloudService>();
  final FileManagerService _fileManagerService = Get.find<FileManagerService>();
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  
  // 搜索关键词
  final RxString _searchKeyword = ''.obs;
  String get searchKeyword => _searchKeyword.value;
  
  // 搜索结果
  final RxList<VirtualFileNode> _searchResults = <VirtualFileNode>[].obs;
  List<VirtualFileNode> get searchResults => _searchResults;
  
  // 搜索历史
  final RxList<String> _searchHistory = <String>[].obs;
  List<String> get searchHistory => _searchHistory;
  
  // 搜索建议
  final RxList<String> _searchSuggestions = <String>[].obs;
  List<String> get searchSuggestions => _searchSuggestions;
  
  // 搜索过滤器
  final Rx<SearchFilter> _searchFilter = SearchFilter().obs;
  SearchFilter get searchFilter => _searchFilter.value;
  
  // 搜索状态
  final RxBool _isSearching = false.obs;
  bool get isSearching => _isSearching.value;
  
  // 是否有搜索结果
  final RxBool _hasSearched = false.obs;
  bool get hasSearched => _hasSearched.value;
  
  // 选中的搜索结果
  final RxList<VirtualFileNode> _selectedResults = <VirtualFileNode>[].obs;
  List<VirtualFileNode> get selectedResults => _selectedResults;
  
  // 是否显示高级搜索
  final RxBool _showAdvancedSearch = false.obs;
  bool get showAdvancedSearch => _showAdvancedSearch.value;
  
  // 搜索排序方式
  final RxString _sortBy = 'relevance'.obs;
  String get sortBy => _sortBy.value;
  
  @override
  void onInit() {
    super.onInit();
    _loadSearchHistory();
  }
  
  // 加载搜索历史
  Future<void> _loadSearchHistory() async {
    try {
      final history = _preferencesService.getSearchHistory();
      _searchHistory.value = history;
    } catch (e) {
      print('加载搜索历史失败: $e');
    }
  }
  
  // 保存搜索历史
  Future<void> _saveSearchHistory() async {
    try {
      await _preferencesService.setSearchHistory(_searchHistory);
    } catch (e) {
      print('保存搜索历史失败: $e');
    }
  }
  
  // 搜索文件
  Future<void> searchFiles(String keyword) async {
    if (keyword.trim().isEmpty) {
      clearSearch();
      return;
    }
    
    _searchKeyword.value = keyword.trim();
    _isSearching.value = true;
    _hasSearched.value = true;
    
    try {
      // 添加到搜索历史
      _addToSearchHistory(keyword);
      
      List<VirtualFileNode> results = [];
      
      // 根据搜索范围进行搜索
      switch (_searchFilter.value.scope) {
        case SearchScope.local:
          results = await _searchLocalFiles(keyword);
          break;
        case SearchScope.cloud:
          results = await _searchCloudFiles(keyword);
          break;
        case SearchScope.all:
          final localResults = await _searchLocalFiles(keyword);
          final cloudResults = await _searchCloudFiles(keyword);
          results = [...localResults, ...cloudResults];
          // 去重
          results = _removeDuplicates(results);
          break;
      }
      
      // 应用过滤器
      results = _applyFilters(results);
      
      // 排序
      _sortResults(results, keyword);
      
      _searchResults.value = results;
      
    } catch (e) {
      _showError('搜索失败', e.toString());
      _searchResults.clear();
    } finally {
      _isSearching.value = false;
    }
  }
  
  // 搜索本地文件
  Future<List<VirtualFileNode>> _searchLocalFiles(String keyword) async {
    return await _databaseService.searchFiles(keyword);
  }
  
  // 搜索云端文件
  Future<List<VirtualFileNode>> _searchCloudFiles(String keyword) async {
    try {
      return await _cloudService.searchFiles(keyword);
    } catch (e) {
      print('搜索云端文件失败: $e');
      return [];
    }
  }
  
  // 去重
  List<VirtualFileNode> _removeDuplicates(List<VirtualFileNode> files) {
    final seen = <String>{};
    return files.where((file) {
      final key = '${file.name}_${file.path}';
      if (seen.contains(key)) {
        return false;
      }
      seen.add(key);
      return true;
    }).toList();
  }
  
  // 应用过滤器
  List<VirtualFileNode> _applyFilters(List<VirtualFileNode> files) {
    var filtered = files;
    
    // 文件类型过滤
    if (_searchFilter.value.type != SearchType.all) {
      filtered = filtered.where((file) => _matchesFileType(file, _searchFilter.value.type)).toList();
    }
    
    // 路径过滤
    if (_searchFilter.value.path != null && _searchFilter.value.path!.isNotEmpty) {
      filtered = filtered.where((file) => file.path.startsWith(_searchFilter.value.path!)).toList();
    }
    
    // 日期过滤
    if (_searchFilter.value.startDate != null) {
      filtered = filtered.where((file) => 
        file.createdTime.isAfter(_searchFilter.value.startDate!)
      ).toList();
    }
    
    if (_searchFilter.value.endDate != null) {
      filtered = filtered.where((file) => 
        file.createdTime.isBefore(_searchFilter.value.endDate!.add(const Duration(days: 1)))
      ).toList();
    }
    
    // 大小过滤（需要获取文件元数据）
    // 这里简化处理，实际应该异步获取文件大小
    
    return filtered;
  }
  
  // 检查文件类型匹配
  bool _matchesFileType(VirtualFileNode file, SearchType type) {
    if (type == SearchType.folder) {
      return file.isFolder;
    }
    
    if (file.isFolder) {
      return false;
    }
    
    final fileName = file.name.toLowerCase();
    
    switch (type) {
      case SearchType.image:
        return fileName.endsWith('.jpg') || fileName.endsWith('.jpeg') || 
               fileName.endsWith('.png') || fileName.endsWith('.gif') ||
               fileName.endsWith('.bmp') || fileName.endsWith('.webp');
      case SearchType.video:
        return fileName.endsWith('.mp4') || fileName.endsWith('.avi') ||
               fileName.endsWith('.mkv') || fileName.endsWith('.mov') ||
               fileName.endsWith('.wmv') || fileName.endsWith('.flv');
      case SearchType.audio:
        return fileName.endsWith('.mp3') || fileName.endsWith('.wav') ||
               fileName.endsWith('.flac') || fileName.endsWith('.aac') ||
               fileName.endsWith('.ogg') || fileName.endsWith('.m4a');
      case SearchType.document:
        return fileName.endsWith('.pdf') || fileName.endsWith('.doc') ||
               fileName.endsWith('.docx') || fileName.endsWith('.txt') ||
               fileName.endsWith('.rtf') || fileName.endsWith('.odt');
      case SearchType.archive:
        return fileName.endsWith('.zip') || fileName.endsWith('.rar') ||
               fileName.endsWith('.7z') || fileName.endsWith('.tar') ||
               fileName.endsWith('.gz') || fileName.endsWith('.bz2');
      case SearchType.other:
        return !_matchesFileType(file, SearchType.image) &&
               !_matchesFileType(file, SearchType.video) &&
               !_matchesFileType(file, SearchType.audio) &&
               !_matchesFileType(file, SearchType.document) &&
               !_matchesFileType(file, SearchType.archive);
      default:
        return true;
    }
  }
  
  // 排序搜索结果
  void _sortResults(List<VirtualFileNode> results, String keyword) {
    switch (_sortBy.value) {
      case 'relevance':
        _sortByRelevance(results, keyword);
        break;
      case 'name':
        results.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
        break;
      case 'date':
        results.sort((a, b) => b.createdTime.compareTo(a.createdTime));
        break;
      case 'size':
        // 需要获取文件大小，这里暂时按名称排序
        results.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
        break;
    }
  }
  
  // 按相关性排序
  void _sortByRelevance(List<VirtualFileNode> results, String keyword) {
    final lowerKeyword = keyword.toLowerCase();
    
    results.sort((a, b) {
      final aName = a.name.toLowerCase();
      final bName = b.name.toLowerCase();
      
      // 完全匹配优先
      if (aName == lowerKeyword && bName != lowerKeyword) return -1;
      if (bName == lowerKeyword && aName != lowerKeyword) return 1;
      
      // 开头匹配优先
      final aStartsWith = aName.startsWith(lowerKeyword);
      final bStartsWith = bName.startsWith(lowerKeyword);
      if (aStartsWith && !bStartsWith) return -1;
      if (bStartsWith && !aStartsWith) return 1;
      
      // 包含匹配
      final aContains = aName.contains(lowerKeyword);
      final bContains = bName.contains(lowerKeyword);
      if (aContains && !bContains) return -1;
      if (bContains && !aContains) return 1;
      
      // 文件夹优先
      if (a.isFolder && !b.isFolder) return -1;
      if (b.isFolder && !a.isFolder) return 1;
      
      // 按名称排序
      return aName.compareTo(bName);
    });
  }
  
  // 获取搜索建议
  Future<void> getSuggestions(String input) async {
    if (input.trim().isEmpty) {
      _searchSuggestions.clear();
      return;
    }
    
    final suggestions = <String>{};
    
    // 从搜索历史中获取建议
    for (final history in _searchHistory) {
      if (history.toLowerCase().contains(input.toLowerCase())) {
        suggestions.add(history);
      }
    }
    
    // 从文件名中获取建议
    try {
      final files = await _databaseService.getAllFiles();
      for (final file in files) {
        if (file.name.toLowerCase().contains(input.toLowerCase())) {
          suggestions.add(file.name);
        }
      }
    } catch (e) {
      print('获取文件建议失败: $e');
    }
    
    _searchSuggestions.value = suggestions.take(10).toList();
  }
  
  // 添加到搜索历史
  void _addToSearchHistory(String keyword) {
    if (_searchHistory.contains(keyword)) {
      _searchHistory.remove(keyword);
    }
    _searchHistory.insert(0, keyword);
    
    // 限制历史记录数量
    if (_searchHistory.length > 20) {
      _searchHistory.removeRange(20, _searchHistory.length);
    }
    
    _saveSearchHistory();
  }
  
  // 清除搜索
  void clearSearch() {
    _searchKeyword.value = '';
    _searchResults.clear();
    _selectedResults.clear();
    _hasSearched.value = false;
    _isSearching.value = false;
  }
  
  // 清除搜索历史
  void clearSearchHistory() {
    _searchHistory.clear();
    _saveSearchHistory();
  }
  
  // 删除搜索历史项
  void removeSearchHistoryItem(String item) {
    _searchHistory.remove(item);
    _saveSearchHistory();
  }
  
  // 设置搜索过滤器
  void setSearchFilter(SearchFilter filter) {
    _searchFilter.value = filter;
    
    // 如果有搜索关键词，重新搜索
    if (_searchKeyword.value.isNotEmpty) {
      searchFiles(_searchKeyword.value);
    }
  }
  
  // 切换高级搜索
  void toggleAdvancedSearch() {
    _showAdvancedSearch.value = !_showAdvancedSearch.value;
  }
  
  // 设置排序方式
  void setSortBy(String sortBy) {
    _sortBy.value = sortBy;
    
    // 重新排序当前结果
    if (_searchResults.isNotEmpty) {
      _sortResults(_searchResults, _searchKeyword.value);
      _searchResults.refresh();
    }
  }
  
  // 选择搜索结果
  void selectResult(VirtualFileNode file) {
    if (_selectedResults.contains(file)) {
      _selectedResults.remove(file);
    } else {
      _selectedResults.add(file);
    }
  }
  
  // 全选搜索结果
  void selectAllResults() {
    _selectedResults.clear();
    _selectedResults.addAll(_searchResults);
  }
  
  // 取消选择
  void clearSelection() {
    _selectedResults.clear();
  }
  
  // 导航到文件位置
  Future<void> navigateToFile(VirtualFileNode file) async {
    try {
      final parentPath = file.path.substring(0, file.path.lastIndexOf('/'));
      await _fileManagerService.navigateToPath(parentPath.isEmpty ? '/' : parentPath);
      
      // 切换到文件管理页面
      Get.back(); // 返回到主页面
      // 这里可以添加切换到文件管理tab的逻辑
      
    } catch (e) {
      _showError('导航失败', e.toString());
    }
  }
  
  // 获取搜索统计信息
  Map<String, dynamic> getSearchStatistics() {
    final typeCount = <String, int>{};
    
    for (final file in _searchResults) {
      String type;
      if (file.isFolder) {
        type = 'folder';
      } else {
        final fileName = file.name.toLowerCase();
        if (_matchesFileType(file, SearchType.image)) {
          type = 'image';
        } else if (_matchesFileType(file, SearchType.video)) {
          type = 'video';
        } else if (_matchesFileType(file, SearchType.audio)) {
          type = 'audio';
        } else if (_matchesFileType(file, SearchType.document)) {
          type = 'document';
        } else if (_matchesFileType(file, SearchType.archive)) {
          type = 'archive';
        } else {
          type = 'other';
        }
      }
      
      typeCount[type] = (typeCount[type] ?? 0) + 1;
    }
    
    return {
      'keyword': _searchKeyword.value,
      'total_results': _searchResults.length,
      'selected_count': _selectedResults.length,
      'type_count': typeCount,
      'search_scope': _searchFilter.value.scope.toString(),
      'search_type': _searchFilter.value.type.toString(),
      'sort_by': _sortBy.value,
      'history_count': _searchHistory.length,
    };
  }
  
  // 显示错误信息
  void _showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
}